
/* 公共request 方法 */
const msdjs = require('./md5.js');
 function getQueryString(name,url,ture) {
	 if(ture){
		  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	 }else{
		  var reg = new RegExp('(^|/?)' + name + '=([^&]*)(&|$)', 'i');
	 }
      var r = url.substr(1).match(reg);
      if(r != null) {
        return unescape(r[2]);
      }
      return null;
  }
   
const requestUrl = function(url){
	let data={};
	var header = {
	    'content-type': 'application/x-www-form-urlencoded',
	   }
	let  timestamp = Date.parse(new Date());
	timestamp = timestamp / 1000;
	//data.api_member_id = uni.getStorageSync('api_member_id') ? uni.getStorageSync('api_member_id') : "0";
	data.api_time = timestamp;
	//data.api_member_name=uni.getStorageSync('api_member_name') ? uni.getStorageSync('api_member_name') : "0";
	let unionId = uni.getStorageSync("unionId")?uni.getStorageSync("unionId") : "";
	data.op=getQueryString("op",url,true) || index;
	data.act=getQueryString("act",url,false);
	data.buss_type=getQueryString("buss_type",url,false)
	data.comefrom="WAP"
	  let APIKEY = "AWAP78851ERFG85"
	// #ifdef APP-PLUS
			uni.getSystemInfo({
				success: (res) => {
					if (res.platform == "android") {
						data.comefrom = "Android";
					}else{
						data.comefrom = "IOS";
					}
				}
			})
			APIKEY = "ANHK78451ERFG17"
		// #endif
		// #ifdef H5
		let ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			data.comefrom = "WeChat";
			APIKEY = "AWECHAT788NDG85"
		} else {
			data.comefrom = "WAP";
			APIKEY = "AWAP78851ERFG85"
		}
		// #endif
		// #ifdef MP-WEIXIN
			data.comefrom = "APPLET";
			APIKEY = "LET78451EHMG63"
		// #endif
	
	if(data.op!="goods_list"&&data.act!="goods"){
		  data.key=uni.getStorageSync("key") || "0";
	}
		  
	// 接口签名 
	let api_signMd5=ksort(data);
	
	let  forinstring="";
	console.log(data)
		
		for( let key in api_signMd5){
			if(key!="file" && key!="avator"){
				forinstring+="&"+key+"="+encodeURI(api_signMd5[key])
			}
		}
	api_signMd5= forinstring.replace("&","")+APIKEY;
	api_signMd5=api_signMd5.replace(/,/g,"%2C")
	api_signMd5=api_signMd5.replace(/@/g,"%40")
	api_signMd5=api_signMd5.replace(/\//g,"%2F")
	api_signMd5=api_signMd5.replace(/:/g,"%3A")
	
	data.api_sign = msdjs.hexMD5(api_signMd5);
	
	data.api_sign = msdjs.hexMD5(api_signMd5).toUpperCase()
	data.api_sign= data.api_sign.toLocaleLowerCase()
	
	return data;
}

/* 公共showTotast  loading 方法 */
module.exports = {
  request: requestUrl,
};

function ksort(o) {
  let sorted = {},
  keys = Object.keys(o);
  keys.sort();
  keys.forEach((key)=>{
    sorted[key] = o[key];
  })
  return sorted;
}